package com.hnzq.cloud.freshorderassembly.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnzq.cloud.api.FreGoodsAPI;
import com.hnzq.cloud.dto.*;
import com.hnzq.cloud.freshorderassembly.domain.FreShopcar;
import com.hnzq.cloud.freshorderassembly.exception.ShopcarGoodsException;
import com.hnzq.cloud.freshorderassembly.mapper.FreShopcarMapper;
import com.hnzq.cloud.freshorderassembly.service.IFreShopcarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hnzq.cloud.freshorderassembly.util.WoniuBeanUtils;
import com.hnzq.cloud.model.Result;
import com.hnzq.cloud.param.AddShopcarGoodsParam;
import com.hnzq.cloud.param.UpdateGoodsCountParam;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 周皓月
 * @since 2022-02-06
 */
@Service
public class FreShopcarServiceImpl extends ServiceImpl<FreShopcarMapper, FreShopcar> implements IFreShopcarService {

    @Resource
    private FreShopcarMapper shopcarMapper;

    @Resource
    private FreGoodsAPI goodsAPI;

    /**
     * 类型转换器
     */
    ObjectMapper mapper = new ObjectMapper();



    /**
     * 查询当前用户的购物车列表
     * @return
     */
    @Override
    public PageShopcarGoodsDto findShopcarGoods() {

        //从登录中获取到userId
        Integer userId = mapper.convertValue(((ServletRequestAttributes)
                (RequestContextHolder.currentRequestAttributes())).getRequest()
                .getHeader("userId"), Integer.class);

        //根据条件进行分页查询
        IPage<FreShopcar> iPage = page(new Page<>(1
                , 2), new QueryWrapper<FreShopcar>().eq("user_id",userId));

        PageShopcarGoodsDto pageShopcarGoodsDto = new PageShopcarGoodsDto();
        pageShopcarGoodsDto.setCurrent(iPage.getCurrent());
        pageShopcarGoodsDto.setTotal(iPage.getTotal());
        pageShopcarGoodsDto.setShopcarGoodsDtoList
                (WoniuBeanUtils.copyList(shopcarMapper.FindShopcarGoods(userId), ShopcarGoodsDto.class));

        return pageShopcarGoodsDto;
    }


    /**
     * 操作购物车，修改商品数量
     * @param updateGoodsCountParam
     * @return
     */
    @Override
    public UpdateGoodsCountDto updateGoodsCount(UpdateGoodsCountParam updateGoodsCountParam) {

        //从登录中获取到userId
        Integer userId = mapper.convertValue(((ServletRequestAttributes)
                (RequestContextHolder.currentRequestAttributes())).getRequest()
                .getHeader("userId"), Integer.class);

        FreShopcar goodsDB = getOne(new QueryWrapper<FreShopcar>()
                .eq("shopcar_id",updateGoodsCountParam.getShopcarId())
                .eq("user_id",userId));

        if (goodsDB == null){
            throw new ShopcarGoodsException("购物车商品不存在",2001);
        }
        FreShopcar shopcar = WoniuBeanUtils.copyObject(updateGoodsCountParam, FreShopcar.class);
        shopcar.setUserId(userId);

        //执行修改操作
        saveOrUpdate(shopcar);
        UpdateGoodsCountDto ugcDto = new UpdateGoodsCountDto();
        ugcDto.setGoodsId(goodsDB.getGoodsId());
        ugcDto.setGoodsName(goodsDB.getGoodsName());
        ugcDto.setGoodsCount(updateGoodsCountParam.getGoodsCount());
        return ugcDto;
    }

    /**
     * 操作购物车，删除商品
     * @param goodsId
     * @return
     */
    @Override
    public Boolean removeGoods(Integer goodsId) {

        //从登录中获取到userId
        Integer userId = mapper.convertValue(((ServletRequestAttributes)
                (RequestContextHolder.currentRequestAttributes())).getRequest()
                .getHeader("userId"), Integer.class);


        FreShopcar goodsDB = getOne(new QueryWrapper<FreShopcar>()
                .eq("goods_id", goodsId)
                .eq("user_id",userId));

        if (goodsDB == null){
            throw new ShopcarGoodsException("购物车商品不存在",2001);
        }
        //执行删除
        return removeById(goodsId);
    }

    /**
     * 向购物车里添加商品信息
     * @param addShopcarGoodsParam
     * @return
     */
    @Override
    public AddShopcarGoodsDto addShopcarGoods(AddShopcarGoodsParam addShopcarGoodsParam) {

        //从登录中获取到userId
        Integer userId = mapper.convertValue(((ServletRequestAttributes)
                (RequestContextHolder.currentRequestAttributes())).getRequest()
                .getHeader("userId"), Integer.class);

        Result result = goodsAPI.findFreGoodsInfo(addShopcarGoodsParam.getGoodsId());
        Object data = result.getData();
        if (data == null){
            throw new ShopcarGoodsException("商品不存在",2002);
        }

        //转换result
        FreGoodsDto freGoodsDto = mapper.convertValue(data, new TypeReference<FreGoodsDto>() {});

        FreShopcar shopcarDB = getOne
                (new QueryWrapper<FreShopcar>().eq("goods_id", addShopcarGoodsParam.getGoodsId()));
        if (shopcarDB != null){
            //原有数量 + 参数数量
            shopcarDB.setGoodsCount(shopcarDB.getGoodsCount() + addShopcarGoodsParam.getGoodsCount());
            addShopcarGoodsParam.setGoodsName(freGoodsDto.getGoodsName());
            //执行新增操作
            saveOrUpdate(shopcarDB);
            return WoniuBeanUtils.copyObject(addShopcarGoodsParam,AddShopcarGoodsDto.class);
        }

        addShopcarGoodsParam.setGoodsName(freGoodsDto.getGoodsName());
        FreShopcar shopcar = WoniuBeanUtils.copyObject(addShopcarGoodsParam, FreShopcar.class);
        shopcar.setUserId(userId);
        //执行新增操作
        saveOrUpdate(shopcar);
        return WoniuBeanUtils.copyObject(addShopcarGoodsParam,AddShopcarGoodsDto.class);
    }
}
